package com.cty.A_OutOfMemoryError.E_DirectMemoryOOM;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * @Auther: cty
 * @Date: 2020/6/26 22:32
 * @Description: 直接内存溢出——OutOfMemoryError
 * @VM Args: -Xmx20M -XX:MaxDirectMemorySize=10M
 * @version: 1.0
 */
public class DirectMemoryOOM {

    private static final int _1MB = 1024*1024;

    public static void main(String[] args) throws IllegalAccessException {
        Field unsafeField = Unsafe.class.getDeclaredFields()[0];
        unsafeField.setAccessible(true);
        Unsafe unsafe = (Unsafe)unsafeField.get(null);
        while(true){
            unsafe.allocateMemory(_1MB);
        }
    }  // end main()
}  // end DirectMemoryOOM{}

/**
 * Exception in thread "main" java.lang.OutOfMemoryError
 * 	at sun.misc.Unsafe.allocateMemory(Native Method)
 * 	at com.cty.OutOfMemoryError.E_DirectMemoryOOM.DirectMemoryOOM.main(DirectMemoryOOM.java:23)
 */
